package main

import (
	"database/sql"
	"fmt"
	"go.uber.org/zap"
	"google.golang.org/protobuf/proto"
	"laxkits/lib/laxmysql"
	"laxkits/lib/laxutils"
	KKSG "laxkits/lib/ropb"
)

func TryModify(conn *laxmysql.LaxMySQLConn) {
	if conn == nil {
		return
	}
	var err error
	var role RoleItemReadNode
	role.Init()
	for i := 0; i < 5; i++ {
		zap.S().Infof("conn:%s, 开始查询role%d", conn.GetId(), i)
		qsql := fmt.Sprintf("select serverid,id,name,account, ItemDataList_0, ItemDataList_1,ItemDataList_2,ItemDataList_3,ItemDataList_4 from player%d.role", i)
		if err = conn.LaxQuery(qsql, func(row *sql.Rows) error {
			if err = row.Scan(role.rowFields...); err != nil {
				zap.S().Warn("查询失败,", err)
				return err
			}
			role.Parse()
			for j := 0; j < 5; j++ {
				var pb KKSG.ItemDataList_0
				if err = proto.Unmarshal(role.GetItemData(j), &pb); err != nil {
					zap.S().Warn("序列化成pb失败:", err)
					return err
				}
				if pb.ItemDataList == nil || pb.ItemDataList.ItemDataList == nil {
					return nil
				}
				needModify := false
				for idx, item := range pb.ItemDataList.ItemDataList {
					if (item.StateSign & 1) == 1 { // 绑定改成非绑
						if _, ok := laxutils.ROGlobalConfigNode.ItemIdMap[item.ItemId]; ok {
							zap.S().Infof("%s 需要修改道具:%d uid:%d 绑定:%d, player:%d, itemidx:%d", role.String(), item.ItemId, item.Uid, item.StateSign, i, j)
							pb.ItemDataList.ItemDataList[idx].StateSign ^= 1
							needModify = true
						}
					}
				}
				if needModify {
					var dataList []byte
					if dataList, err = proto.Marshal(&pb); err != nil {
						zap.S().Warnf("写入数据失败: 修改后pb序列化失败:%v", err)
						return err
					}
					msql := fmt.Sprintf("update player%d.role set ItemDataList_%d = ? where id = ?", i, j)
					var affect int64
					if affect, err = conn.LaxExecute(msql, dataList, role.Id); err != nil {
						zap.S().Warn("执行修改的sql出错:", err)
						return err
					}
					zap.S().Infof("%s 列:%d,修改成功,影响行:%d", role.String(), j, affect)
				}
			}
			//zap.S().Infof("%d,%s,%s 道具列:%d 有%d个道具", id, name, account, j,cnt)
			return nil
		}); err != nil {
			zap.S().Info("总执行出错:", err)
			return
		}
	}
}
